<?php
/**
 * This file contains all code of the index controller
 *
 * Index controller will controll the login/logout action and initialize the session for logged users
 *
 * LICENSE: Proprietary software licenses
 *
 * @copyright 2008 VMG Media
 * @license Proprietary
 *
 */

/**
 * IndexController class
 *
 * The class for all session initialization actions
 *
 */
class IndexController extends Zend_Controller_Action
{
	/**
	 * index action
	 *
	 */
	function indexAction()
	{
		$this->_redirect("index/login");
	}

	/**
	 * Recovery action
	 *
	 * Username/password recovery action
	 *
	 */
	function recoveryAction(){

	}

	/**
	 * Enter description here...
	 *
	 */
	function loginAction(){
		$this->view->title = "Login page";

		$auth = Zend_Auth::getInstance();
		if($auth->hasIdentity()){
			$user = $auth->getIdentity();
			$user_default_values = $user->getDefaultValues();
			$this->_redirect($user_default_values["controller"] . "/" . $user_default_values["action"] );
		}
		$registry = Zend_Registry::getInstance();
		$others_config = $registry->get('others_config');
		$this->view->back_link = $others_config->vmg_home;
		$form = new LoginForm();
		$users = new Users();
		$this->view->form = $form;
		$this->view->message = '';
		if($this->_request->isPost()){
			$formData = $this->_request->getPost();

			if($form->isValid($formData)){


				$dbAdapter = $users->getAdapter();

				// Set up the authentication adapter
				$authAdapter = new Zend_Auth_Adapter_DbTable(
				    $dbAdapter,
				    'vmg_user',
				    'username',
				    'password'
				);
				//$auth->setStorage(new Zend_Auth_Storage_Session('VMG'));
				// Set up the authentication input
				$username = $this->_request->getPost('username');
				$password = $this->_request->getPost('password');

				$authAdapter->setIdentity($username)
    						->setCredential(md5($password));

				$result = $auth->authenticate($authAdapter);
				if (!$result->isValid()) {
				    // Authentication failed; print the reasons why
				    foreach ($result->getMessages() as $message) {
				        $this->view->message .=  $this->view->translate($message) ;
				    }
				} else {
					// redirect
					$user = new Member($authAdapter->getResultRowObject(array('id', 'name', 'type_id', 'username', 'managed_by' )));
					$auth->getStorage()->write($user);
					$user_default_values = $user->getDefaultValues();
					$this->_redirect($user_default_values["controller"] . "/" . $user_default_values["action"] );
				}
			} else {
				$form->populate($formData);
			}
		} else {
		}
		$this->_helper->layout->setLayout('one_column');
	}

	/**
	 * logout action
	 *
	 */
	function logoutAction(){
		$auth = Zend_Auth::getInstance();
		$auth->clearIdentity();
		$this->_redirect("index/login");
	}
}

